<script lang="ts">
import { defineComponent, h, ref } from "vue";

interface ShowInterface {
    show: {
        name: string;
        image: {
            medium: string;
        };
    };
}

export default defineComponent({
    name: "RenderMenu",

    setup(props, { slots }) {
        // const $http = inject("$http"); 全局注入

        let inputValue = "";
        let shows = ref<null | []>(null);
        let error = ref<null | string>(null);

        const searchText = async (search: string) => {
            if (!search) return;
            shows.value = [];
            console.log("got here", search);

            const searchT = await axios.get(
                `http://api.tvmaze.com/search/shows?q=${search}`
            );

            shows.value = searchT.data;
            console.log(shows.value);
        };

        // * slots 内的数据是通过函数返回的，所以获取具体的插槽内容需要使用方法，slots.slotName()
        const slot = slots.default ? slots.default() : [];
        const namedSlot = slots.namedSlot ? slots.namedSlot() : [];

        // named slot sc
        // * 作用域插槽使用方式
        const sc = (show: any) => (slots.sc ? slots.sc(show) : []);

        console.log({ sc });

        return () =>
            h(
                "form",
                {
                    style: "color: red; max-width:768px; margin: auto",
                    onSubmit: (event: Event) => event.preventDefault(), // 阻止表单提交默认行为，默认会刷新页面
                },
                // * 顺序会影响元素的位置
                [
                    slot,
                    namedSlot,
                    sc({ shows: shows.value }),
                    h("input", {
                        onChange: (event: any) => {
                            console.log({ event });
                            inputValue = event.target.value;
                        },
                    }),
                    h(
                        "button",
                        {
                            onClick: async () => {
                                searchText(inputValue);
                            },
                        },
                        "Press Me"
                    ),
                    h("div", { class: "shows" }, [
                        error.value
                            ? h("div", error.value)
                            : shows.value?.map((show: ShowInterface) =>
                                  h("div", { class: "show" }, [
                                      h("div", show.show.name),
                                      h("img", {
                                          src: show.show.image?.medium,
                                      }),
                                  ])
                              ),
                    ]),
                ]
            );
    },
});
</script>

<style lang="scss" scoped>
.show {
    margin: 10px;
    min-width: 210px;
}
.shows {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    justify-content: center;
}
</style>
